<?php

namespace app\admin\controller;

use app\models\ArrangingModel;
use app\models\CampusModel;
use app\models\ClassRoomModel;
use app\models\CourseModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\HolidayModel;
use app\models\RemedialModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\UserModel;

/**
 * Class Remedial
 * @package app\admin\controller
 */
class Remedial extends Common
{

    /**
     * 班级管理列表详情模型.
     *
     * @var GradesDetailsListsModel
     */
    protected $gradesdetaillistModel;

    /**
     * 学生分班管理模型.
     *
     * @var StudentSubjectClassModel
     */
    protected $studentsubjectclassModel;

    /**
     * 教室模型.
     *
     * @var ClassRoomModel
     */
    protected $classroomModel;

    /**
     * 课程模型.
     *
     * @var CourseModel
     */
    protected $courseModel;


    /**
     * 校区模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * RemedialModel 排课模型.
     *
     * @var RemedialModel
     */
    protected $remedialModel;


    /**
     * 节假日管理模型.
     *
     * @var HolidayModel
     */
    protected $holidayModel;

    /**
     * 学生分班排课管理模型.
     *
     * @var StudentSubjectInfosClassModel
     */
    protected $studentsubjectinfosclassModel;


    /**
     * 班级管理详情模型.
     *
     * @var GradesDetailsModel
     */
    protected $gradesdetailModel;
    /**

    /**
     * 排课管理.
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */


    //节假日信息
    protected $holiday_arr = [];


    //排课详情信息
    protected $course_lists_arr = [];



    //已报课程详情信息
    protected $course_assignment_arr = [];

    //课程名称信息表
    protected $course_id_name_arr = [];

    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $course =  $this->studentsubjectinfosclassModel->Makeuplessons($param);
            $this->success('success', '', $course, 0);
        }
        $where = [];
        $course_where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$where['id'] = get_current_campus_id();
			$course_where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$where['id'] = ['in',get_current_campus_id()];
			$course_where['campus_id'] = ['in',get_current_campus_id()];
		}
        $campus = $this->campusModel->where($where)->select()->toArray();
        $course_list = $this->courseModel->where($course_where)->select();
        return $this->fetch('',['course_list' => $course_list,'campus' => $campus]);
    }

    /**
     * 添加排课.
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
//            if (!$this->courseValidate->scene('add')->check($data)) {
//                $this->error($this->courseValidate->getError(), null, '', 1);
//            }
            $data['campus_id'] = get_current_campus_id();
            $data['cost_type'] = 89;
            $data['price'] = $data['price'] * 100;
            $res = $this->remedialModel->save($data);
            $course['id'] = $this->remedialModel->id;
            $course['course_name'] = $this->remedialModel->course_name;
            if (!$res) {
                $this->error('添加排课失败', null, '', 1);
            }
            $this->success('添加成功', '', $course, 1);
        }
        $this->dictionary();
        return $this->fetch('',['year'=>date('Y')]);
    }

    /**
     * 改变状态
     *
     * @return \think\response\Json
     */
    public function arranging_check_status()
    {
        if (request()->isPost()) {
            try {
                $data = input('post.');
                if ($data['status'] == 0) {
                    $msg = '禁用';
                } else {
                    $msg = '启用';
                }
                CourseModel::update($data);
                return json(['code' => 0, 'msg' => $msg]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }
    }


    //跟班补课逻辑
    public function follow_grade(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $ids = $data['ids']; //补课列表id，用逗号连接
            $ids_arr = explode(',',$ids); //分割成数组
            $id = $data['id']; //所跟课节id
			$course_where = [];
			$course_where['campus_id'] = $data['campus_id'];
            $result = $this->studentsubjectinfosclassModel->where($course_where)->select();
            $result_gradeslist = $this->gradesdetaillistModel->get(['id' => $id]);  //班级id

            $save_student_data = [];  //学生表
            $save_infos_data = []; //学生上课详情表

            foreach ($result as $key => $value){
                if(in_array($value['id'],$ids_arr)){   //包含在数组内
                    //edu_class_subject_student
                    $item = [];
                    $item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $item['student_id'] = $value['student_id'];
                    $item['student_name'] = $value['student_name'];
                    $item['student_type'] = 3;  //补课学生
                    $item['room_id'] = $result_gradeslist['class_room_id'];  //教室ID
                    $item['campus_id'] = $data['campus_id'];
                    $item['contract_number'] = $value['contract_number'];
                    $item['status'] = $value['report_status'];  //1:课程分配  2:班级分配  3:试听分配
                    $save_student_data[] = $item;

                    //edu_class_subject_student_infos
                    $info_item = [];
                    $info_item['class_manage_details_id'] = $id;
                    $info_item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $info_item['student_id'] = $value['student_id'];
                    $info_item['student_name'] = $value['student_name'];
                    $info_item['room_name'] = $result_gradeslist['class_room'];
                    $info_item['weekday'] = $result_gradeslist['weekday'];
                    $info_item['class_date'] = $result_gradeslist['class_date'];
                    $info_item['course_id'] = $result_gradeslist['course_id'];
                    $info_item['contract_number'] = $value['contract_number'];
                    $info_item['room_id'] = $result_gradeslist['class_room_id'];
                    $info_item['attendance'] = $value['attendance'];  //考勤状态
                    $info_item['charging'] = $value['charging'];  //计费状态
                    $info_item['campus_id'] = $value['campus_id'];

                    $start = strtotime($result_gradeslist['class_subject_start']);  //开始时间
                    $end = strtotime($result_gradeslist['class_subject_end']);  //结束时间

                    $duration = ceil(($end - $start)/60); //节课时长
                    $info_item['duration'] = $duration;

                    $info_item['eliminated_nums'] = $value['eliminated_nums'];
                    $info_item['surplus_class_elimination'] = $value['surplus_class_elimination'];
                    $info_item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                    $info_item['report_status'] = $value['report_status'];
                    $info_item['give_status'] = $value['give_status'];
                    $info_item['amount_deducted'] = $value['amount_deducted'];
                    $info_item['status'] = 0;
                    $info_item['lessons_status'] = 0;
                    $info_item['lessons_id'] = $value['id'];
                    //操作人
                    $info_item['operatorer'] = get_current_name();  //操作人

                    $info_item['follow_status'] = 2; //跟班课节

                    $save_infos_data[] = $info_item;

                    //更新补课状态
                    if(!$this->studentsubjectinfosclassModel->where(['id' => $value['id']])->update(['lessons_status' => 1])){

                        $this->error('更新跟班补课状态失败', null, '', 1);
                    }

                }
            }

            if(count($save_student_data) > 0){
                if(!$this->studentsubjectclassModel->insertAll($save_student_data)){
                    $this->error('插入学生信息失败', null, '', 1);
                }
            }

            if(count($save_infos_data) > 0){
                if(!$this->studentsubjectinfosclassModel->insertAll($save_infos_data)){
                    $this->error('插入学生课节详情信息失败', null, '', 1);
                }
            }

            $this->success('跟班补课成功', '', '', 1);
        }

    }


    //删除补课记录
    public function del_class(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $ids = $data['ids']; //补课列表id，用逗号连接
            if(!$this->studentsubjectinfosclassModel->where("id in ($ids)")->delete()){
                $this->error('删除补课记录记录', null, '', 1);
            }
            $this->success('删除补课记录成功', '', '', 1);
        }


    }


    //跟班补课
    public function follow_class(){

        $ids = input('ids'); //补课记录自增ID
        $class_subject_id = input('class_subject_id'); //对应的班级Id
        $course_id = input('course_id'); //课程ID
        $campus_id = input('campus_id'); //校区ID
        $ids_arr = explode(',',$ids); //分割成数组
		$course_where = [];
		$course_where['campus_id'] = $campus_id;
		$result = $this->studentsubjectinfosclassModel->where($course_where)->select();
        $student_name_arr = [];
        foreach ($result as $key => $value){
            if(in_array($value['id'],$ids_arr)){   //包含在数组内
                $student_name_arr[] = $value['student_name'];  //学生姓名
            }
        }
		$where = [];
		$where['id'] = $campus_id;
		$where['status'] = 1;
        $campuslist = $this->campusModel->get($where);//获取校区
        $student_name_arr_str = json_encode($student_name_arr);

        return $this->fetch('',['class_subject_id' => $class_subject_id, 'campuslist' => $campuslist,'student_name_arr' =>$student_name_arr_str, 'course_id' =>$course_id, 'campus_id' =>$campus_id,  'ids' => $ids]);
    }

    //新建班级补课
    public function lesson_class(){

        $ids = input('ids'); //补课记录自增ID
        $course_id = input('course_id'); //课程ID
        $campus_id =  input('campus_id'); //补课校区ID
        $campus_name = $this->campusModel->get(['id' => $campus_id])['campus_name'];
        $ids_arr = explode(',',$ids); //分割成数组
		$course_where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$course_where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$course_where['campus_id'] = ['in',get_current_campus_id()];
		}
		$result = $this->studentsubjectinfosclassModel->where($course_where)->select();
        $student_name_arr = [];
        foreach ($result as $key => $value){
            if(in_array($value['id'],$ids_arr)){   //包含在数组内
                $student_name_arr[] = $value['student_name'];  //学生姓名
            }
        }
        //生成班级名字
        $course_name= $this->courseModel->get(['id' => $course_id])['course_name'];
        $course_name = $course_name.'_补课班级';
		$gradesdetail = [];
		$gradesdetail['grades_name'] = ['like', $course_name.'%'];
		/*
		if(get_current_type() == 4 || get_current_type() == 5){
			$gradesdetail['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$gradesdetail['campus_id'] = ['in',get_current_campus_id()];
		}
		*/
        $count = $this->gradesdetailModel->where($gradesdetail)->count();

		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$where['id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
		$campuslist = $this->campusModel->where($where)->select();//获取校区列表

        $class_where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$class_where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$class_where['campus_id'] = ['in',get_current_campus_id()];
		}
        $class_where['seat_set'] = ['neq',''] ;
		$class_where['campus_id'] = $campus_id;
        $classroomlist = $this->classroomModel->where($class_where)->select();//获取教室列表


        $student_name_arr_str = json_encode($student_name_arr);

        return $this->fetch('',['campus_id' => $campus_id , 'campus_name' => $campus_name, 'campuslist' => $campuslist,'student_name_arr' =>$student_name_arr_str, 'course_id' =>$course_id, 'count' => $count,  'ids' => $ids,  'classroomlist' => $classroomlist]);
    }

    //将数据插入学生分配表,节课表
    public function insert_student_infos(){
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $ids = $data['ids'];
            $grades_name = $data['grades_name'];//补课班级名称
            $campus_id = $data['campus_id']; //补课校区ID
            $ids_arr = explode(',',$ids); //分割成数组
            $lesson_status = [];
            for ($g = 0; $g < count($ids_arr); $g ++){
                $item = [];
                $item['id'] = $ids_arr[$g];
                $item['lessons_status'] = 1;
                $lesson_status[] = $item;
            }

            $info_result = $this->studentsubjectinfosclassModel->where("id in ($ids)")->select();
            $result = $this->gradesdetailModel->get(['grades_name' => $grades_name]); //获取补课班级的名称对应的信息
            $result_detail_list = $this->gradesdetaillistModel->get(['class_manage_id' =>$result['id'] ]);  //班级节课ID

            //遍历选中的同学
            $student_save_date = [];  //edu_class_subject_student
            $info_save_class_date = []; //edu_class_subject_student_infos
            foreach ($info_result as $key => $value){
                    $item = [];
                    $item['class_subject_id'] = $result['id']; // 班课表ID
                    $item['student_id'] =  $value['student_id']; //学生ID
                    $item['student_name'] = $value['student_name']; //学生姓名
                    $item['campus_id'] = $campus_id;  //补课校区ID
                    $item['room_id']  = $result['room_id']; //教室id
                    $item['student_type'] = 3; //补课类型
                    $item['status'] = $value['report_status'];  //1:课程  2:班级  3:试听
                    $item['contract_number'] = $value['contract_number']; //合同号
                    $student_save_date[] = $item;


                    $cell = [];
                    $cell['contract_number'] = $value['contract_number'];  //订单编号ID，非自增ID
                    $cell['student_id'] = $value['student_id'];  //学生ID
                    $cell['student_name'] = $value['student_name']; //学生姓名
                    $cell['surplus_class_elimination'] = $value['surplus_class_elimination']; //剩余课时
                    $cell['surplus_class_elimination_give'] = $value['surplus_class_elimination_give']; //赠送剩余课时
                    $cell['charging'] = $value['charging'];  //计费
                    $cell['eliminated_nums'] = $value['eliminated_nums'];  //课消数量，默认为0
                    $cell['amount_deducted'] = $value['amount_deducted'];  //扣除金额
                    $cell['room_id'] = $result['room_id'];;//教室ID
                    $cell['class_subject_id'] = $result['id'];//班级ID
                    $cell['class_manage_details_id'] = $result_detail_list['id']; //ID
                    $cell['room_name'] = $result['room_text']; //教室名称
                    $cell['report_status'] = $value['report_status'];  //1:课程  2:班级  3:试听
                    $cell['campus_id'] = $campus_id;  //补课校区ID
                     //操作人
                    $cell['operatorer'] = get_current_name();  //操作人

                    $cell['class_date'] = $result['class_start_date']; //开班日期
                    $cell['course_id'] = $result['course_id']; //课程ID

                    $start = strtotime($result_detail_list['class_subject_start']);  //开始时间
                    $end = strtotime($result_detail_list['class_subject_end']);  //结束时间
                    $cell['duration'] = ceil(($end - $start)/60);//上课时长

                    $cell['lessons_id'] = $value['id'];  //补课对象的自增ID
                    $cell['weekday'] = $result_detail_list['weekday']; //星期

                    $cell['follow_status'] = 1; //新开班课节

                    $info_save_class_date[] = $cell;
            }



            if(count($student_save_date) > 0) {
                if (!$this->studentsubjectclassModel->insertAll($student_save_date)) {
                    $this->error('补课分班失败', null, -1, 1);
                }

            }


            if(count($info_save_class_date) > 0){
                if (!$this->studentsubjectinfosclassModel->insertAll($info_save_class_date)) {
                    $this->error('补课详情课节生成失败', null, -1, 1);
                }
            }

            //修改开班状态
            $result_ = $this->studentsubjectclassModel->where(['class_subject_id' => $result['id']])->select();
            if(count($result_) > 0){
                if(!$this->gradesdetailModel->update(['status' => 1],['id' => $result['id']])){
                    $this->error('更新补课开班记录失败', null, -1, 1);
                }

            }else{
                if(!$this->gradesdetailModel->update(['status' => 0],['id' => $result['id']])){
                    $this->error('更新补课开班记录失败', null, -1, 1);
                }
            }

            if(!$this->gradesdetailModel->update(['class_status' => 1],['id' => $result['id']])){
                $this->error('更新补课班级状态失败', null, -1, 1);
            }
            if(!$this->studentsubjectinfosclassModel->saveAll($lesson_status)){
                $this->error('更新班级对应课程补课状态失败', null, -1, 1);
            }



            $this->success('补课学生分班成功', '', '', 1);
        }

    }

    /***
     *
     * 把班级插入数据库
     **/
    public function addclassdata(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            //获取节假日信息
            if(count($this->holiday_arr) <= 0){
                $campus_id = $this->courseModel->get(['id' => $data['course_id']])['campus_id'];
                $company_id = $this->campusModel->get(['id' => $campus_id])['company_id'];  //系统ID
                $result_msg = $this->holidayModel->where(['company_id'=>$company_id])->select();
                foreach ($result_msg as $key=>$value){
                    $this->holiday_arr[] = $value['date_name'];
                }
            }
            $status_num = input('status');
            $conflict =  input('conflict');
            //修改逻辑
            $modify_status = false;
            $manage_id = -1000;
            if(isset($_GET["manage_id"])){//是否存在"id"的参数
                $manage_id = input('manage_id');  //班级id
                $modify_status = true;
            }

            $course_id = $data['course_id'];  //课程id

            $holiday_status = $data['holiday_status']; //是否跳过节假日
            $grades_name = $data['grades_name'];//班级名称
            $headmaster = $data['headmaster'];//班主任
            $preoccupation = $data['preoccupation'];//预招学生
            $teacher = $data['teacher'];//任课老师
            $assistant = $data['assistant'];//助教
            $class_start_date = $data['class_start_date'];//计划开班
            $class_end_date = $data['class_end_date'];//计划结业
            $remarks = $data['remarks'];//备注
            $repeat_status = $data['repeat_status'];//重复类型；1：按周重复，2：按日重复
            $project_num = $data['project_num'];//计划课次
            $interval_value = $data['interval_value'];//重复间隔值：周重复则按根据interval_value的值来间隔重复;日重复则根据interval_value值间隔重复；默认间隔值为0
            $user_master_id = $data['user_master_id']; //班主任ID
            $teacher_id = $data['teacher_id']; //任课老师ID
            $assistant_id = $data['assistant_id']; //助教ID
            $res_teacher = UserModel::get(['teacher_id' => $teacher_id, 'group_type' => 2]);
            $user_teacher_id = $res_teacher ? $res_teacher['id'] : null;
            $res_assistant = UserModel::get(['teacher_id' => $teacher_id, 'group_type' => 3]);
            $user_assistant_id = $res_assistant ? $res_assistant['id'] : null;


            $campus_id = $data['campus_id']; //
            $classdata = $data['classdata'];  //排课数据
            //        dp($classdata);
            $json_str = json_decode($classdata, true);
            if(count($json_str) <= 0){
                $this->error('请选择上课时间', null, -1, 1);
            }

            $str = "";
            $weekday_arr = [];
            $room_text_str = "";
            $room_id_str = "";
            $time_slot = "";
            $week_record = "";
            $start_day_class = "";
            $weekarray=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六"); //先定义一个数组
            $start_postion = date("w",strtotime($class_start_date));
            for($i = 0 ; $i < count($json_str); $i ++){
                $item = $json_str[$i];
                $weekday = "";
                $weekday_mysql = "";
                if($repeat_status == 2){  //按日
                    $start_day_class = $item['weekday'];
                    $weekday = $weekarray[date("w",strtotime($item['weekday']))];
                }else if ($repeat_status == 1){  //按周
                    $weekday = $item['weekday'];
                    $weekday_mysql =  $item['weekday'];
                }
                $start_time = $item['start_time'];
                $end_time = $item['end_time'];
                $room_text = $item['room_text'];
                $room_id = $item['room_id'];
                if($repeat_status == 2){  //按日
                    $weekday = $item['weekday'].'--每隔'.$interval_value.'日';
                    $weekday_mysql = $item['weekday'];
                }
                $str = $str."【".$weekday.'--'.$start_time.'--'.$end_time.'--'.$room_text."】";
                $room_id_str = $room_id_str.','.$room_id;  //教室
                $room_text_str = $room_text_str.','.$room_text; //教室名称
                $week_record = $week_record.','.$weekday_mysql;  //星期
                $time_slot = $time_slot.','.$start_time.'-'.$end_time; //开始结束时间
            }

            $room_id_str = trim($room_id_str);
            $room_text_str = trim($room_text_str);
            $week_record = trim($week_record);
            $time_slot = trim($time_slot);

            $room_id_str = substr($room_id_str, 1, strlen($room_id_str));
            $room_text_str = substr($room_text_str, 1, strlen($room_text_str));
            $week_record = substr($week_record, 1, strlen($week_record));
            $time_slot = substr($time_slot, 1, strlen($time_slot));

            $class_time_place = $str;
            $already_class = "";//已排次数
            $already_arranged = "";//上课进度，已上次数
            $status = ""; //0：未上课，1：上课中
            $public_end_date = "";
            $have_end_date_status = false; //表示设置在了结束日期

            if($class_end_date == ""){  //未填写结业日期
                $public_end_date =  NULL;
            }else{
                $public_end_date = $class_end_date;
                $have_end_date_status = true;
            }

            //保存gradesdetailModel数据
            $savedata = array(

                'campus_id' => $campus_id,
                'course_id' => $course_id,
                'grades_name' => $grades_name,
                'headmaster' => $headmaster,
                'preoccupation' => $preoccupation,
                'teacher' => $teacher,
                'assistant' => $assistant,
                'holiday_status' => $holiday_status,
                'class_start_date'=> $class_start_date,
                'class_end_date' => $public_end_date,
                'remarks' => $remarks,
                'repeat_status' => $repeat_status,
                'project_num' => $project_num,
                'interval_value' => $interval_value,
                'room_id' => $room_id_str,
                'week_record' => $week_record,
                'time_slot' => $time_slot,
                'room_text' => $room_text_str,
                'class_time_place' => $class_time_place,
                'user_master_id' => $user_master_id,
                'teacher_id' => $teacher_id,
                'assistant_id' => $assistant_id,
                'user_teacher_id' => $user_teacher_id,
                'user_assistant_id' => $user_assistant_id,
                'user_edu_id' => get_current_id(),  //教务ID

            );

            if(!$modify_status){
                if($this->gradesdetailModel->get(['grades_name' => $grades_name,'campus_id' =>$campus_id])){  //判断班级名称是否重复
                    $this->error('班级名字重复', null, -1, 1);
                }
            }


            $result = $this->gradesdetailModel->create($savedata);
            if (!$result) {
                $this->error('排班失败', null, -1, 1);
            } else {
                //插入班级详情表
                $savedata_list = [];
                $public_headmaster = $headmaster;  //公共班主任
                $public_teacher = $teacher;  //公共任课老师
                $public_assistant = $assistant;  //公共助教
                $public_campus_id = $campus_id;  //公共校区
                $public_course_id = $course_id;  //公共课程
                $public_grades = $grades_name;  //公共班级名称


                $init_day = "";
                if($repeat_status == 1){
                    $init_day = $class_start_date; //开始日期
                }else if($repeat_status == 2){
                    $init_day = $start_day_class; //开始日期
                }
                $timestamp = strtotime($init_day);

                for($num = 1; $num <= $project_num;) {


                    if($repeat_status == 1) {   //如果是按周重复
                        $postion = date("w",$timestamp);
                        $same_day = date("Y-m-d", $timestamp);
                        $public_end_date = $same_day;

                        if($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) &&  $status_num == 2){  //填了结业日期

                            $sure_nums = $num-1; //可排次数
                            $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                            $this->success('最多可排【'.$sure_nums.'】次课', url('Remedial/lists'), $sure_nums, 1);
                        }else if($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date)  &&  $status_num == 1){
                            $already_class =  $num-1; //可排次数;
                            break;
                        }


                        for($i = 0 ; $i < count($json_str); $i ++) {
                            $item = $json_str[$i];
                            $weekday = $item['weekday'];
                            if($weekarray[$postion] == $weekday) {
                                if($num -1 >= $project_num){
                                    $already_class =  $num-1; //可排次数;
                                    break;
                                }
                                //判断是否跳过节假日
                                if($holiday_status == 1){  //跳过节假日
                                    if(in_array($same_day,$this->holiday_arr)){
                                        break;
                                    }
                                }

                                $data = array();
                                $data['class_manage_id'] = $result['id'];
                                $data['headmaster'] = $public_headmaster;
                                $data['teacher'] = $public_teacher;
                                $data['assistant'] = $public_assistant;
                                $data['course_id'] = $public_course_id;
                                $data['campus_id'] = $public_campus_id;
                                $data['class_grades_name'] = $public_grades;
                                $data['class_date'] = $same_day;
                                $data['weekday'] = $item['weekday'];
                                $data['class_room_id'] = $item['room_id'];
                                $data['class_subject_start'] = $item['start_time'];
                                $data['class_subject_end'] = $item['end_time'];
                                $data['class_room'] = $item['room_text'];

                                //判断冲突
                                if($this->judgement_conflict($data,$modify_status, $manage_id) == 1 && $conflict == 2){
                                    //助教冲突
                                    $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                    $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---助教*【'.$public_assistant.'】冲突';
                                    $this->success($msg, url('Remedial/lists'), 10001, 1);
                                }else if($this->judgement_conflict($data,$modify_status, $manage_id) == 2 && $conflict == 2){
                                    //老师冲突
                                    $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                    $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---任课老师*【'.$public_teacher.'】冲突';
                                    $this->success($msg, url('Remedial/lists'), 10001, 1);
                                }else if($this->judgement_conflict($data,$modify_status, $manage_id) == 3 && $conflict == 2){
                                    //教室冲突
                                    $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                    $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---教室*【'. $item['room_text'].'】冲突';
                                    $this->success($msg, url('Remedial/lists'), 10001, 1);
                                }else if(($this->judgement_conflict($data,$modify_status, $manage_id) == 1 || $this->judgement_conflict($data,$modify_status, $manage_id) == 2 || $this->judgement_conflict($data,$modify_status, $manage_id) == 3) && $conflict == 3){


                                }else{
                                    $savedata_list[] = $data;
                                    $num++;
                                }
                                /*
                                $savedata_list[] = $data;
                                $num ++;
                                */

                            }
                        }

                        if($postion == 0){  //周日
                            $days_add = $interval_value * 7;
                            $timestamp = strtotime('+'.$days_add.'days', $timestamp);
                        }
                        $timestamp = strtotime('+1days', $timestamp);


                    }else if($repeat_status == 2) {  //如果是按天重复

                        $same_day = date("Y-m-d", $timestamp);
                        $public_end_date = $same_day;


                        if ($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) && $status_num == 2) {  //填了结业日期
                            $sure_nums = $num - 1; //可排次数
                            $this->gradesdetailModel->where(['id' => $result['id']])->delete();
                            $this->success('最多可排【' . $sure_nums . '】次课', url('Remedial/lists'), $sure_nums, 1);
                        } else if ($have_end_date_status && strtotime($class_end_date) < strtotime($public_end_date) && $status_num == 1) {
                            $already_class = $num - 1; //可排次数;
                            break;
                        }


                        $weekday = $weekarray[date("w", $timestamp)];
                        //判断是否跳过节假日
                        $bool_holiday = false;
                        if ($holiday_status == 1) {  //跳过节假日
                            if (in_array($same_day, $this->holiday_arr)) {
                                /*
                                $timestamp = strtotime('+1days', $timestamp);
                                */
                                $bool_holiday = true;
                            }
                        }

                        if (!$bool_holiday) {
                            $data = array();
                            $data['class_manage_id'] = $result['id'];
                            $data['headmaster'] = $public_headmaster;
                            $data['teacher'] = $public_teacher;
                            $data['assistant'] = $public_assistant;
                            $data['course_id'] = $public_course_id;
                            $data['campus_id'] = $public_campus_id;
                            $data['class_grades_name'] = $public_grades;
                            $data['class_date'] = $same_day;
                            $data['weekday'] = $weekday;
                            $data['class_room_id'] = $item['room_id'];
                            $data['class_subject_start'] = $item['start_time'];
                            $data['class_subject_end'] = $item['end_time'];
                            $data['class_room'] = $item['room_text'];

                            //判断冲突
                            if($this->judgement_conflict($data,$modify_status, $manage_id) == 1 && $conflict == 2){
                                //助教冲突
                                $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---助教*【'.$public_assistant.'】冲突';
                                $this->success($msg, url('Remedial/lists'), 10001, 1);
                            }else if($this->judgement_conflict($data,$modify_status, $manage_id) == 2 && $conflict == 2){
                                //老师冲突
                                $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---任课老师*【'.$public_teacher.'】冲突';
                                $this->success($msg, url('Remedial/lists'), 10001, 1);
                            }else if($this->judgement_conflict($data,$modify_status, $manage_id) == 3 && $conflict == 2){
                                //教室冲突
                                $this->gradesdetailModel->where(['id'=> $result['id']])->delete();
                                $msg = '忽略--【'.$same_day.'】--时间段:【'.$item['start_time'].'--'.$item['end_time'].'】---教室*【'. $item['room_text'].'】冲突';
                                $this->success($msg, url('Remedial/lists'), 10001, 1);
                            }else if(($this->judgement_conflict($data,$modify_status, $manage_id) == 1 || $this->judgement_conflict($data,$modify_status, $manage_id) == 2 || $this->judgement_conflict($data,$modify_status, $manage_id) == 3) && $conflict == 3){


                            }else{
                                $savedata_list[] = $data;
                                $num++;
                            }

                        }


                        $days_add = $interval_value * 1;
                        $timestamp = strtotime('+' . $days_add . 'days', $timestamp);
                        $timestamp = strtotime('+1days', $timestamp);

                    }

                }

                $already_class = $num - 1; //可排次数;

                if($class_end_date == ""){
                    $this->gradesdetailModel->save(['class_end_date' => $public_end_date],['id' => $result['id']]);
                    $already_class = $project_num;
                }

                $this->gradesdetailModel->save(['already_class' => $already_class],['id' => $result['id']]); //更新可排次数

                if(count($savedata_list) > 0) {
                    if (!$this->gradesdetaillistModel->insertAll($savedata_list)) {
                        $this->error('补课排班失败', null, -1, 1);
                    }
                }


            }
            if($modify_status){
                $this->gradesdetailModel->where(['id' => $manage_id])->delete();
                $this->gradesdetaillistModel->where(['class_manage_id' => $manage_id])->delete();
                $this->success('补课修改成功', url('Remedial/lists'), -1, 1);
            }
            $this->success('补课排班成功', url('Remedial/lists'), -1, 1);

        }

    }

    /****
     * 排课冲突判断
     */
    public function judgement_conflict($course_item,$modify_status, $manage_id){

        $status_course = false;
        $current_campus_id = get_current_campus_id(); //当前校区

        for($a = 0; $a < count($this->course_lists_arr); $a ++){

            if($modify_status && $this->course_lists_arr[$a]['class_manage_id'] == $manage_id){
                continue;
            }

            if($this->course_lists_arr[$a]['campus_id'] == $current_campus_id){  //校区是否相同
                if($this->course_lists_arr[$a]['class_date'] == $course_item['class_date']){ //日期是否相同

                    $course_list_start_timestamp = strtotime($this->course_lists_arr[$a]['class_subject_start']);  //课程开始时间
                    $course_list_end_timestamp = strtotime($this->course_lists_arr[$a]['class_subject_end']);  //课程结束时间
                    $course_item_start_timestamp = strtotime($course_item['class_subject_start']);  //课程开始时间
                    $course_item_end_timestamp = strtotime($course_item['class_subject_end']);  //课程结束时间

                    if($this->course_lists_arr[$a]['class_room_id'] == $course_item['class_room_id']){  //教室是否相同

                        //判断教室是否冲突
                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                            if($this->course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                                //1.判断老师时间是否冲突
                                //2.如果老师时间不冲突则比较助教是否相
                                //3.比较助教相同的条件下时间是否冲突

                                if($course_item_end_timestamp <= $course_list_start_timestamp){
                                    //任课老师时间不冲突
                                    if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }


                                    }else{
                                        //可排
                                        $status_course = false;
                                    }

                                }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                    //任课老师时间不冲突
                                    if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }



                                    }else{
                                        //可排
                                        $status_course = false;
                                    }


                                }else{
                                    //不可排
                                    $status_course = true;
                                    return  2;   //老师时间冲突
                                }



                            }else if($this->course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                                if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                    //比时间
                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else{
                                        //不可排
                                        $status_course = true;
                                        return  1;   //助教时间冲突
                                    }

                                }

                            }

                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){

                            if($this->course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                                //1.判断老师时间是否冲突
                                //2.如果老师时间不冲突则比较助教是否相
                                //3.比较助教相同的条件下时间是否冲突

                                if($course_item_end_timestamp <= $course_list_start_timestamp){
                                    //任课老师时间不冲突
                                    if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }


                                    }else{
                                        //可排
                                        $status_course = false;
                                    }

                                }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                    //任课老师时间不冲突
                                    if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                        if($course_item_end_timestamp <= $course_list_start_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                            //可排
                                            $status_course = false;
                                        }else{

                                            //不可排
                                            $status_course = true;
                                            return  1;   //助教时间冲突
                                        }



                                    }else{
                                        //可排
                                        $status_course = false;
                                    }


                                }else{
                                    //不可排
                                    $status_course = true;
                                    return  2;   //老师时间冲突
                                }



                            }else if($this->course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                                if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                    //比时间
                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //可排
                                        $status_course = false;

                                    }else{
                                        //不可排
                                        $status_course = true;
                                        return  1;   //助教时间冲突
                                    }

                                }

                            }
                        }else{
                            //不可排
                            $status_course = true;
                            return  3;   //教室时间冲突
                        }


                    }else if($this->course_lists_arr[$a]['class_room_id'] != $course_item['class_room_id']){  //教室不同
                        if($this->course_lists_arr[$a]['teacher'] == $course_item['teacher']){  //任课老师是否相同
                            //1.判断老师时间是否冲突
                            //2.如果老师时间不冲突则比较助教是否相同
                            //3.比较助教相同的条件下时间是否冲突
                            if($course_item_end_timestamp <= $course_list_start_timestamp){
                                //任课老师时间不冲突
                                if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //可排
                                        $status_course = false;
                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //可排
                                        $status_course = false;
                                    }else{

                                        //不可排
                                        $status_course = true;
                                        return  1;   //助教时间冲突
                                    }


                                }else{
                                    //可排
                                    $status_course = false;
                                }

                            }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                //任课老师时间不冲突
                                if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){
                                    if($course_item_end_timestamp <= $course_list_start_timestamp){
                                        //可排
                                        $status_course = false;
                                    }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                        //可排
                                        $status_course = false;
                                    }else{

                                        //不可排
                                        $status_course = true;
                                        return  1;   //助教时间冲突
                                    }



                                }else{
                                    //可排
                                    $status_course = false;
                                }


                            }else{
                                //不可排
                                $status_course = true;
                                return  2;   //老师时间冲突
                            }



                        }else if($this->course_lists_arr[$a]['teacher'] != $course_item['teacher']){
                            if($this->course_lists_arr[$a]['assistant'] == $course_item['assistant']){  //助教老师是否相同
                                //比时间是否冲突
                                if($course_item_end_timestamp <= $course_list_start_timestamp){
                                    //可排
                                    $status_course = false;

                                }else if($course_item_start_timestamp >= $course_list_end_timestamp){
                                    //可排
                                    $status_course = false;

                                }else{
                                    //不可排
                                    $status_course = true;
                                    return  1;   //助教时间冲突
                                }


                            }
                        }

                    }

                }

            }


        }


        return -1;
    }

    /**
     * 实例化.
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->remedialModel = new RemedialModel();
        $this->campusModel = new CampusModel();
        $this->classroomModel = new ClassRoomModel();
        $this->studentsubjectinfosclassModel = new StudentSubjectInfosClassModel();
        $this->gradesdetailModel = new GradesDetailsModel();
        $this->studentsubjectclassModel = new StudentSubjectClassModel();
        $this->gradesdetaillistModel = new GradesDetailsListsModel();
        $this->holidayModel = new HolidayModel();
        $this->courseModel = new CourseModel();

        //获取节假日信息
        if(count($this->holiday_arr) <= 0){
            $result_msg = $this->holidayModel->select();
            foreach ($result_msg as $key=>$value){
                $this->holiday_arr[] = $value['date_name'];
            }
        }


        //排课详情信息
        $result_course_lists = $this->gradesdetaillistModel->select();
        array_splice($this->course_lists_arr, 0, count($this->course_lists_arr));  //清空数组
        foreach ($result_course_lists as $key=>$value){
            $item = [];
            $item['class_date'] = $value['class_date']; //开课日期
            $item['class_manage_id'] = $value['class_manage_id']; //教室管理详情表自增id
            $item['course_id'] = $value['course_id']; //课程ID
            $item['campus_id'] = $value['campus_id']; //归属校区
            $item['weekday'] = $value['weekday']; //星期
            $item['headmaster'] = $value['headmaster']; //班主任
            $item['teacher'] = $value['teacher']; //任课老师
            $item['assistant'] = $value['assistant']; //助教
            $item['class_grades_name'] = $value['class_grades_name']; //班级名称
            $item['class_subject_start'] = $value['class_subject_start']; //上课开始时间
            $item['class_subject_end'] = $value['class_subject_end']; //上课结束时间
            $item['class_room_id'] = $value['class_room_id']; //教室id
            $item['class_room'] = $value['class_room']; //教室名称
            $item['status'] = $value['status']; //上课状态
            $this->course_lists_arr[] = $item;
        }


    }
}
